package com.mapa.dao;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.mopa.shopping.entidades.Usuario;


public class DAO
{
	private EntityManagerFactory entityManagerFactory = null;

	private EntityManager entityManager = null;

	private EntityTransaction transaction = null;

	public DAO ()
	{
		entityManagerFactory = Persistence.createEntityManagerFactory( "postgres" );
		entityManager = entityManagerFactory.createEntityManager();
	}

	public DAO ( String nomeDaPersistenceUnit )
	{
		entityManagerFactory = Persistence
				.createEntityManagerFactory( nomeDaPersistenceUnit );
		entityManager = entityManagerFactory.createEntityManager();
	}

	public DAO ( EntityManagerFactory emf )
	{
		entityManagerFactory = emf;
		entityManager = entityManagerFactory.createEntityManager();
	}

	public DAO ( EntityManager em )
	{
		entityManager = em;
	}

	public Usuario salvar ( Usuario entidade )
	{
		try
		{
			transaction = entityManager.getTransaction();

			transaction.begin();
			entityManager.persist( entidade );
			transaction.commit();
		}
		catch ( RuntimeException e )
		{
			if ( transaction.isActive() )
			{
				transaction.rollback();
			}
		}

		return entidade;
	}

}